#include "LinkList_nohead.h"

static LinkList_t * tail = NULL;
static LinkList_t * head = NULL;
static int list_length = 0;

//头插
int LinkList_nohead_headinsert(int data){
    LinkList_t * p = (LinkList_t *)malloc(sizeof(LinkList_t));
    if(p==NULL){
        LOG("item create failed\n");
        return -1;
    }
    p->data = data;
    if(list_length==0){
        p->next = NULL;
        head = p;
    }else{
        LinkList_t * q = head;
        p->next = q;
        head = p;
    }
    list_length++;
    return 0;
}

//尾插
int LinkList_nohead_tailinsert(int data){
    LinkList_t * p = (LinkList_t *)malloc(sizeof(LinkList_t));
    if(p==NULL){
        LOG("item create failed\n");
        return -1;
    }
    p->data = data;
    if(list_length == 0){
        p->next = NULL;
        tail = p;
        head = p;
    }else{
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    list_length ++;
    return 0;
}

//删除指定节点
int LinkList_nohead_delitem(int index){
    if(head==NULL){
        return -1;
    }
    int i = 0;

    if(index == i){
        LinkList_t *q =head->next;
        free(head);
        head = q;
    }

    i++;

    LinkList_t * p = head->next;
    LinkList_t * prev = head;
    while(p!=NULL){
        if(i==index){
            prev->next = p->next;
            free(p);
            p = NULL;
            break;
        }
        p = p->next;
        prev = prev ->next;
        i++;
    }
    return 0;
}

//回收链表
int LinkList_nohead_destory(){
    LinkList_t * p = head;
    while (p!=NULL)
    {
        LinkList_t * q = p->next;
        free(p);
        p = q;
    }
    return 0;
}

int LinkList_nohead_select(){
    LinkList_t * p  = head;
    while(p!=NULL){
        printf("[%d]->",p->data);
        p = p->next;
    }
    printf("NULL\n");
    return 0;
}

